package com.tusuo.stds.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.biz.CurrentUser;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.rest.AppInfo;
import com.tusuo.stds.ui.fillinfo.FillInfoActivity_;
import com.tusuo.stds.ui.register.RegisterActivity_;
import com.tusuo.stds.ui.resetpassword.ResetPasswordActivity_;
import com.tusuo.stds.util.DoubleClickExitDetector;
import com.tusuo.stds.util.IntentUtils;
import com.tusuo.stds.util.Utils;


import org.parceler.Parcels;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(LoginPresenter.class)
class LoginPresenter extends MvpBasePresenter<LoginView> {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    DoubleClickExitDetector mDoubleClickExitDetector;
    @Inject
    CurrentUser mCurrentUser;

    private Context mContext;
    private String mErrMsgServer;

    private ThirdLoginUserInfo mThirdLoginUserInfo;

    private Handler mHandlerShowErrMsg;
    private Subscriber<ApiResult> mLoginSubscriber = null;
    private Subscriber<ApiResult> mThirdLoginSubscriber = null;

    LoginPresenter(Context context) {
        mContext = context;
        mHandlerShowErrMsg = new Handler();
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initLoginPresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mHandlerShowErrMsg != null) {
            mHandlerShowErrMsg.removeCallbacksAndMessages(null);
        }
        if (mLoginSubscriber != null) {
            mLoginSubscriber.unsubscribe();
            mLoginSubscriber = null;
        }
        if (mThirdLoginSubscriber != null) {
            mThirdLoginSubscriber.unsubscribe();
            mThirdLoginSubscriber = null;
        }

        super.detachView(retainInstance);
    }

    private Runnable showSloganRunnable = new Runnable() {
        @Override
        public void run() {
            if (getView() != null) {
                getView().showSlogan();
            }
        }
    };

    void showErrMsg(String text) {
        if (getView() != null) {
            getView().showErrMsg(text);
            mHandlerShowErrMsg.postDelayed(showSloganRunnable, 3000);
        }
    }

    void register() {
        mContext.startActivity(new Intent(mContext, RegisterActivity_.class));
    }

    void resetPassword() {
        mContext.startActivity(new Intent(mContext, ResetPasswordActivity_.class));
    }

    void login(String mobileNo, String password) {
        mLoginSubscriber = new LoginSubscriber();
        mApiHelper.login(mLoginSubscriber, mobileNo, password);
    }

    void thirdLogin(ThirdLoginUserInfo thirdLoginUserInfo) {

        // 别放Toast! ShareSDK会报错！
        mThirdLoginUserInfo = thirdLoginUserInfo;
        mThirdLoginSubscriber = new ThirdLoginSubscriber();
        mApiHelper.thirdLogin(mThirdLoginSubscriber,
                mThirdLoginUserInfo.openId,
                mThirdLoginUserInfo.platForm,
                mThirdLoginUserInfo.accessToken,
                mThirdLoginUserInfo.nickName,
                mThirdLoginUserInfo.userIcon);
    }

    boolean checkDoubleClick() {
        return mDoubleClickExitDetector.click();
    }

    private class LoginSubscriber extends Subscriber<ApiResult> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            showErrMsg(mErrMsgServer);
        }

        @Override
        public void onNext(final ApiResult result) {
            if (result.checkState(mContext)) {
                // Login successfully!
                mApiHelper.getAppInfo(new AppInfoSubscriber());
            } else {
                showErrMsg(result.ErrorMessage);
            }
        }
    }

    private class AppInfoSubscriber extends Subscriber<AppInfo> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(AppInfo appInfo) {
            if (appInfo.checkState(mContext)
                    && !TextUtils.isEmpty(appInfo.CookieName)
                    && !TextUtils.isEmpty(appInfo.UserStatus)) {
                mCurrentUser.setAppInfo(appInfo);
                IntentUtils.toMainActivity(mContext);
            } else {
                Utils.UI.showToastShort(mErrMsgServer);
            }
        }
    }


    private class ThirdLoginSubscriber extends Subscriber<ApiResult> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            showErrMsg(mErrMsgServer);
        }

        @Override
        public void onNext(final ApiResult result) {
            // 未绑定
            if (result.ErrorCode == 500101) {
                Intent intent = new Intent();
                intent.setClass(mContext, FillInfoActivity_.class);
                intent.putExtra(ThirdLoginUserInfo.EXTRA_NAME, Parcels.wrap(mThirdLoginUserInfo));
                mContext.startActivity(intent);
            } else if (result.checkState(mContext)) {
                // Login successfully!
                IntentUtils.toMainActivity(mContext);
            } else {
                showErrMsg(result.ErrorMessage);
            }
        }
    }
}
